//
//  DualMediationMAXRewardedVideoManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/15.
//

#import "DualMediationMAXRewardedVideoManager.h"
#import "DMAdDelegate.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "../../Utils/JSON/DMConfigReader.h"
#import "../../API/AdStrategy/IMSDKStartupConfigManager.h"
#import "DMThinkingManager.h"
#import "DMCommercialManager.h"

#import <FirebaseAnalytics/FirebaseAnalytics.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <AdjustSdk/AdjustSdk.h>

#if __has_include(<UIKit/UIKit.h>)
#import <UIKit/UIKit.h>
#define UIKIT_AVAILABLE 1
#else
#define UIKIT_AVAILABLE 0
#endif

#if __has_include(<AppLovinSDK/AppLovinSDK.h>)
#import <AppLovinSDK/AppLovinSDK.h>
#define APPLOVIN_SDK_AVAILABLE 1
#else
#define APPLOVIN_SDK_AVAILABLE 0
#endif

#if __has_include(<AdjustSdk/AdjustSdk.h>)
#import <AdjustSdk/AdjustSdk.h>
#define ADJUST_SDK_AVAILABLE 1
#else
#define ADJUST_SDK_AVAILABLE 0
#endif

#if __has_include(<FirebaseAnalytics/FIRAnalytics.h>)
#import <FirebaseAnalytics/FIRAnalytics.h>
#define FIREBASE_AVAILABLE 1
#else
#define FIREBASE_AVAILABLE 0
#endif

@interface DualMediationMAXRewardedVideoManager()<MARewardedAdDelegate,MAAdRevenueDelegate>

@property (nonatomic, strong) MARewardedAd *rewardedAd;
// 双广告位支持
@property (nonatomic, strong) MARewardedAd *primaryRewardedAd;
@property (nonatomic, strong) MARewardedAd *secondaryRewardedAd;

@property (nonatomic, assign) BOOL receiveRewardForPlacement;
@property (nonatomic, assign) BOOL hasShowAd;
@property (nonatomic, assign) BOOL isUserClosed;
@property (nonatomic, strong) NSString *currentScene; // 当前展示的场景标识

@end

@implementation DualMediationMAXRewardedVideoManager

static DualMediationMAXRewardedVideoManager *_rewardedVideo = nil;

+ (instancetype)sharedRewardedVideoManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _rewardedVideo = [[self alloc] init];
        [IMLogUtils info:IMLogTagSDKInit format:@"🎬 [MAX Rewarded] 单例管理器创建成功"];
    });
    return _rewardedVideo;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 初始化双广告位支持
        [self initializeDualAdSupport];
    }
    return self;
}

#pragma mark - 双广告位支持方法

- (void)initializeDualAdSupport
{
    [IMLogUtils info:IMLogTagSDKInit format:@"🎬 [MAX Rewarded] 开始初始化双广告位支持"];
    
    // 检查是否启用双广告位
    self.isDualAdEnabled = [DMCommercialManager isDualAdEnabledForAdType:@"rewarded_video"];
    [IMLogUtils info:IMLogTagSDKInit format:@"🎬 [MAX Rewarded] 双广告位启用状态: %@", self.isDualAdEnabled ? @"是" : @"否"];
    
    if (self.isDualAdEnabled) {
        // 获取主备广告位ID
        self.primaryAdUnitId = [DMConfigReader primaryRewardAdUnitIdForMAX];
        self.secondaryAdUnitId = [DMConfigReader secondaryRewardAdUnitIdForMAX];
        
        [IMLogUtils info:IMLogTagSDKInit format:@"🎬 [MAX Rewarded] 主广告位ID: %@", self.primaryAdUnitId ?: @"未配置"];
        [IMLogUtils info:IMLogTagSDKInit format:@"🎬 [MAX Rewarded] 备广告位ID: %@", self.secondaryAdUnitId ?: @"未配置"];
        
        // 设置当前广告位为主广告位
        self.currentAdUnitId = self.primaryAdUnitId;
        self.currentPrimaryAdUnitId = self.primaryAdUnitId;
        self.currentSecondaryAdUnitId = self.secondaryAdUnitId;
        [IMLogUtils info:IMLogTagSDKInit format:@"🎬 [MAX Rewarded] 当前使用广告位: %@", self.currentAdUnitId];
        
        // 初始化重试设置
        [self initializeRetrySettings];
    } else {
        // 单广告位模式，使用原有配置
        NSString *singleAdUnitId = [DMConfigReader primaryRewardAdUnitIdForMAX];
        self.currentAdUnitId = singleAdUnitId;
        self.currentPrimaryAdUnitId = singleAdUnitId;
        [IMLogUtils info:IMLogTagSDKInit format:@"🎬 [MAX Rewarded] 单广告位模式，广告位ID: %@", self.currentAdUnitId];
        
        // 初始化重试设置
        [self initializeRetrySettings];
    }
}

- (void)loadDualRewardedAds
{
    if (!self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 双广告位未启用，跳过双广告位加载"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 开始并行加载主备广告位"];
    
    // 加载主广告位
    [self loadPrimaryRewardedAd];
    
    // 加载备用广告位
    [self loadSecondaryRewardedAd];
}

- (void)loadPrimaryRewardedAd
{
    if (!self.primaryAdUnitId || self.primaryAdUnitId.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] 主广告位ID为空，跳过加载"];
        return;
    }
    
#if APPLOVIN_SDK_AVAILABLE
    dispatch_async(dispatch_get_main_queue(), ^{
        if (!self.primaryRewardedAd) {
            self.primaryRewardedAd = [MARewardedAd sharedWithAdUnitIdentifier:self.primaryAdUnitId];
            self.primaryRewardedAd.delegate = self;
            self.primaryRewardedAd.revenueDelegate = self;
        }
        
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 开始加载主广告位: %@", self.primaryAdUnitId];
        
        // 记录加载请求
        @try {
            NSDictionary *fillRequestParams = @{
                @"w_ad_type": @"rewarded_video",
                @"w_ad_unit_id": self.primaryAdUnitId,
                @"w_ad_scene": @"primary",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_fill_request (主广告位)"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
        }
        
        [self.primaryRewardedAd loadAd];
    });
#endif
}

- (void)loadSecondaryRewardedAd
{
    if (!self.secondaryAdUnitId || self.secondaryAdUnitId.length == 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] 备用广告位ID为空，跳过加载"];
        return;
    }
    
#if APPLOVIN_SDK_AVAILABLE
    dispatch_async(dispatch_get_main_queue(), ^{
        if (!self.secondaryRewardedAd) {
            self.secondaryRewardedAd = [MARewardedAd sharedWithAdUnitIdentifier:self.secondaryAdUnitId];
            self.secondaryRewardedAd.delegate = self;
            self.secondaryRewardedAd.revenueDelegate = self;
        }
        
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 开始加载备用广告位: %@", self.secondaryAdUnitId];
        
        // 记录加载请求
        @try {
            NSDictionary *fillRequestParams = @{
                @"w_ad_type": @"rewarded_video",
                @"w_ad_unit_id": self.secondaryAdUnitId,
                @"w_ad_scene": @"secondary",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_fill_request (备用广告位)"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
        }
        
        [self.secondaryRewardedAd loadAd];
    });
#endif
}

- (void)switchToSecondaryAdIfNeeded
{
    if (!self.isDualAdEnabled) {
        return;
    }
    
    // 检查主广告位是否加载失败且备用广告位就绪
    BOOL primaryFailed = !self.isPrimaryAdLoaded;
    BOOL secondaryReady = self.isSecondaryAdLoaded;
    
    if (primaryFailed && secondaryReady) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 主广告位加载失败，切换到备用广告位"];
        self.currentAdUnitId = self.secondaryAdUnitId;
        
        // 重新加载主广告位
        [self loadPrimaryRewardedAd];
    }
}

- (void)loadDualAdsIfNeeded {
    if (!self.isDualAdEnabled) {
        return;
    }
    
#if APPLOVIN_SDK_AVAILABLE
    dispatch_async(dispatch_get_main_queue(), ^{
        // 加载主广告位
        if (self.primaryAdUnitId && self.primaryAdUnitId.length > 0 && 
            (!self.primaryRewardedAd || !self.primaryRewardedAd.isReady)) {
            if (!self.primaryRewardedAd) {
                self.primaryRewardedAd = [MARewardedAd sharedWithAdUnitIdentifier:self.primaryAdUnitId];
                self.primaryRewardedAd.delegate = self;
                self.primaryRewardedAd.revenueDelegate = self;
            }
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 预加载主广告位: %@", self.primaryAdUnitId];
            [self.primaryRewardedAd loadAd];
        }
        
        // 加载备广告位
        if (self.secondaryAdUnitId && self.secondaryAdUnitId.length > 0 && 
            (!self.secondaryRewardedAd || !self.secondaryRewardedAd.isReady)) {
            if (!self.secondaryRewardedAd) {
                self.secondaryRewardedAd = [MARewardedAd sharedWithAdUnitIdentifier:self.secondaryAdUnitId];
                self.secondaryRewardedAd.delegate = self;
                self.secondaryRewardedAd.revenueDelegate = self;
            }
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 预加载备广告位: %@", self.secondaryAdUnitId];
            [self.secondaryRewardedAd loadAd];
        }
    });
#endif
}

- (void)cleanupAndReloadAds {
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 清理广告对象并重新加载"];
    
    // 清理广告对象
    if (self.isDualAdEnabled) {
        self.primaryRewardedAd = nil;
        self.secondaryRewardedAd = nil;
    }
    self.rewardedAd = nil;
    
    // 重新加载广告
    [self loadRewardedVideo];
}

#pragma mark - 最优广告位选择

/**
 * 选择最优广告位ID
 * 根据广告位可用性选择最优的广告位
 * @return 选择的广告位ID
 */
- (NSString *)selectOptimalAdUnitId {
    if (!self.isDualAdEnabled) {
        return [DMConfigReader primaryRewardAdUnitIdForMAX];
    }
    
    // 检查广告位可用性
    BOOL primaryReady = self.primaryRewardedAd && [self.primaryRewardedAd isReady];
    BOOL secondaryReady = self.secondaryRewardedAd && [self.secondaryRewardedAd isReady];
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 广告位状态检查:"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 主广告位就绪: %@", primaryReady ? @"YES" : @"NO"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 备用广告位就绪: %@", secondaryReady ? @"YES" : @"NO"];
    
    // 如果两个广告位都准备就绪，优先选择主广告位（MAX SDK暂不支持ECPM比较）
    if (primaryReady && secondaryReady) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择主广告位 (两个广告位都可用，优先选择主广告位)"];
        return self.primaryAdUnitId;
    }
    
    if (primaryReady) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择主广告位 (仅主广告位可用)"];
        return self.primaryAdUnitId;
    }
    
    if (secondaryReady) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择备用广告位 (仅备用广告位可用)"];
        return self.secondaryAdUnitId;
    }
    
    // 如果都不可用，默认返回主广告位ID
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 无可用广告位，默认返回主广告位ID"];
    return self.primaryAdUnitId;
}

- (void)setRewardedVideoDelegate
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 开始设置代理和初始化激励视频"];
    
    // 初始化时预加载激励视频广告
    [self loadRewardedVideo];
}

- (void)showRewardedVideo
{
    if (self.isUserClosed) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ 用户已主动关闭广告，拒绝展示"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ========== 开始展示激励视频广告 =========="];
    [[NSUserDefaults standardUserDefaults] setObject:@"2" forKey:@"WDOrientation"];
    
    // 每次展示前重置奖励状态
    self.receiveRewardForPlacement = NO;
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 重置奖励状态: receiveRewardForPlacement = NO"];
    
    // 埋点：SDK_ad_show_request 广告展示请求事件打点
    @try {
        NSDictionary *showRequestParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": @"",
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
#if APPLOVIN_SDK_AVAILABLE
        if (self.rewardedAd && self.rewardedAd.adUnitIdentifier) {
            showRequestParams = @{
                @"w_ad_type": @"rewarded_video",
                @"w_ad_unit_id": self.rewardedAd.adUnitIdentifier,
                @"w_ad_scene": @"default",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
        }
#endif
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_request" properties:showRequestParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_request"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
#if APPLOVIN_SDK_AVAILABLE
    MARewardedAd *adToShow = nil;
    
    // 使用最优广告位选择逻辑
    NSString *selectedAdUnitId = [self selectOptimalAdUnitId];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择的最优广告位: %@", selectedAdUnitId];
    
    if (self.isDualAdEnabled) {
        // 双广告位模式 - 应用FB策略控制
        DMCommercialManager *commercialSDK = [DMCommercialManager sharedInstance];
        
        // 动态检查当前广告位是否应该展示
        BOOL isCurrentSecondary = [selectedAdUnitId isEqualToString:self.secondaryAdUnitId];
        BOOL shouldShow = [commercialSDK shouldShowAd:selectedAdUnitId adType:@"rewarded_video" isSecondaryAdUnit:isCurrentSecondary];
        
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🎯 FB策略检查：当前广告位 %@ (%@)", selectedAdUnitId, isCurrentSecondary ? @"备用" : @"主"];
        
        if (!shouldShow) {
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ⚠️ FB策略控制：当前%@广告位不应展示，尝试切换到另一个广告位", isCurrentSecondary ? @"备用" : @"主"];
            
            // 动态切换到另一个广告位
            NSString *alternativeAdUnitId;
            if ([selectedAdUnitId isEqualToString:self.primaryAdUnitId]) {
                alternativeAdUnitId = self.secondaryAdUnitId;
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔄 从主广告位切换到备用广告位: %@", alternativeAdUnitId];
            } else {
                alternativeAdUnitId = self.primaryAdUnitId;
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔄 从备用广告位切换到主广告位: %@", alternativeAdUnitId];
            }
            
            // 检查切换后的广告位是否可以展示
            BOOL isAlternativeSecondary = [alternativeAdUnitId isEqualToString:self.secondaryAdUnitId];
            BOOL alternativeShouldShow = [commercialSDK shouldShowAd:alternativeAdUnitId adType:@"rewarded_video" isSecondaryAdUnit:isAlternativeSecondary];
            
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🎯 FB策略检查：切换后广告位 %@ (%@)", alternativeAdUnitId, isAlternativeSecondary ? @"备用" : @"主"];
            
            if (alternativeShouldShow) {
                selectedAdUnitId = alternativeAdUnitId;
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ✅ 切换成功：使用%@广告位进行展示", isAlternativeSecondary ? @"备用" : @"主"];
            } else {
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ FB策略控制：所有广告位都不应展示，释放当前广告对象并重新加载"];
                @try {
                    NSDictionary *showFailParams = @{
                        @"w_ad_type": @"rewarded_video",
                        @"w_ad_unit_id": self.rewardedAd ? (self.rewardedAd.adUnitIdentifier ?: @"") : @"",
                        @"w_ad_scene": @"default",
                        @"w_error_code": @"10002",
                        @"w_error_msg": @"FB policy blocked all ad units",
                        @"w_platform": @"MAX",
                        @"w_network": @"AppLovin"
                    };
                    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
                    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_fail"];
                } @catch (NSException *exception) {
                    [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
                }
                
                // 释放当前广告对象并重新加载
                self.primaryRewardedAd = nil;
                self.secondaryRewardedAd = nil;
                self.rewardedAd = nil;
                [self loadRewardedVideo];
                return;
            }
        } else {
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ✅ FB策略检查通过：当前%@广告位可以展示", isCurrentSecondary ? @"备用" : @"主"];
        }
        
        // 根据选择的广告位ID获取对应的广告实例
        if ([selectedAdUnitId isEqualToString:self.primaryAdUnitId] && self.primaryRewardedAd && [self.primaryRewardedAd isReady]) {
            adToShow = self.primaryRewardedAd;
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择主广告位进行展示: %@", selectedAdUnitId];
        } else if ([selectedAdUnitId isEqualToString:self.secondaryAdUnitId] && self.secondaryRewardedAd && [self.secondaryRewardedAd isReady]) {
            adToShow = self.secondaryRewardedAd;
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择备用广告位进行展示: %@", selectedAdUnitId];
        }
        self.currentAdUnitId = selectedAdUnitId;
    } else {
        // 单广告位模式，使用最优广告位选择逻辑
        selectedAdUnitId = [self selectOptimalAdUnitId];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择的最优广告位: %@", selectedAdUnitId];
        
        // 应用FB策略控制
        DMCommercialManager *commercialSDK = [DMCommercialManager sharedInstance];
        BOOL shouldShow = [commercialSDK shouldShowAd:selectedAdUnitId adType:@"rewarded_video" isSecondaryAdUnit:NO];
        
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🎯 FB策略检查：当前广告位 %@ (主)", selectedAdUnitId];
        
        if (!shouldShow) {
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ FB策略控制：主广告位不应展示，释放当前广告对象并重新加载"];
            @try {
                NSDictionary *showFailParams = @{
                    @"w_ad_type": @"rewarded_video",
                    @"w_ad_unit_id": self.rewardedAd ? (self.rewardedAd.adUnitIdentifier ?: @"") : @"",
                    @"w_ad_scene": @"default",
                    @"w_error_code": @"10002",
                    @"w_error_msg": @"FB policy blocked",
                    @"w_platform": @"MAX",
                    @"w_network": @"AppLovin"
                };
                [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_fail"];
            } @catch (NSException *exception) {
                [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
            }
            
            // 释放当前广告对象并重新加载
            self.rewardedAd = nil;
            [self loadRewardedVideo];
            return;
        }
        
        adToShow = self.rewardedAd;
    }
    
    if (adToShow && [adToShow isReady])
    {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ✅ 激励视频广告准备就绪，开始展示"];
        [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 广告实例: %@", adToShow];
        
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 获取根控制器: %@", rootViewController];
        
        [adToShow showAd];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 调用 showAd 完成"];
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ 激励视频广告未准备就绪"];
        [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 广告实例存在: %@", adToShow ? @"YES" : @"NO"];
        [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 广告是否就绪: %@", (adToShow && [adToShow isReady]) ? @"YES" : @"NO"];
        
        // 埋点：SDK_ad_show_fail 广告展示失败事件打点
        @try {
            NSDictionary *showFailParams = @{
                @"w_ad_type": @"rewarded_video",
                @"w_ad_unit_id": adToShow ? (adToShow.adUnitIdentifier ?: @"") : @"",
                @"w_ad_scene": @"default",
                @"w_error_code": @"4001",
                @"w_error_msg": @"Rewarded video ad not ready or not loaded",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_fail"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
        }
        
        self.hasShowAd = YES;
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 设置 hasShowAd = YES，将在广告加载完成后自动展示"];
        [self loadRewardedVideo];
    }
#else
    // 埋点：SDK_ad_show_fail 广告展示失败事件打点
    @try {
        NSDictionary *showFailParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": @"",
            @"w_ad_scene": @"default",
            @"w_error_code": @"3001",
            @"w_error_msg": @"AppLovin SDK not available",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_fail"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
    [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ AppLovin SDK 不可用，无法显示激励视频广告"];
#endif
}

- (void)loadRewardedVideo
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ========== 开始加载激励视频广告 =========="];
    
    if (self.isUserClosed) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 用户已关闭激励视频广告，跳过加载"];
        return;
    }
    
    // 埋点：SDK_ad_fill_request 广告填充请求事件打点
    @try {
        NSDictionary *fillRequestParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": @"",
            @"w_ad_scene": @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
#if APPLOVIN_SDK_AVAILABLE
        NSString *adUnitId = [DMConfigReader primaryRewardAdUnitIdForMAX];
        if (adUnitId) {
            fillRequestParams = @{
                @"w_ad_type": @"rewarded_video",
                @"w_ad_unit_id": adUnitId,
                @"w_ad_scene": @"default",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
        }
#endif
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_fill_request"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
#if APPLOVIN_SDK_AVAILABLE
        if (self.isDualAdEnabled) {
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 双广告位模式 - 创建主备广告实例"];
            
            // 创建主广告位实例
            if (self.primaryAdUnitId && self.primaryAdUnitId.length > 0) {
                self.primaryRewardedAd = [MARewardedAd sharedWithAdUnitIdentifier:self.primaryAdUnitId];
                self.primaryRewardedAd.delegate = self;
                self.primaryRewardedAd.revenueDelegate = self;
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 创建主广告位: %@", self.primaryAdUnitId];
            }
            
            // 创建备广告位实例
            if (self.secondaryAdUnitId && self.secondaryAdUnitId.length > 0) {
                self.secondaryRewardedAd = [MARewardedAd sharedWithAdUnitIdentifier:self.secondaryAdUnitId];
                self.secondaryRewardedAd.delegate = self;
                self.secondaryRewardedAd.revenueDelegate = self;
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 创建备广告位: %@", self.secondaryAdUnitId];
            }
            
            // 设置当前使用的广告实例
            if ([self.currentAdUnitId isEqualToString:self.primaryAdUnitId]) {
                self.rewardedAd = self.primaryRewardedAd;
            } else {
                self.rewardedAd = self.secondaryRewardedAd;
            }
            
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 当前加载广告位: %@", self.currentAdUnitId];
        } else {
            // 单广告位模式
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 单广告位模式 - 创建广告实例"];
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] AdUnit ID: %@", self.currentAdUnitId];
            
            self.rewardedAd = [MARewardedAd sharedWithAdUnitIdentifier:self.currentAdUnitId];
            self.rewardedAd.delegate = self;
            self.rewardedAd.revenueDelegate = self;
        }
        
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 开始加载广告..."];
        [self.rewardedAd loadAd];
#else
        // 埋点：SDK_ad_fill_fail 广告填充失败事件打点
        @try {
            NSDictionary *fillFailParams = @{
                @"w_ad_type": @"rewarded_video",
                @"w_ad_unit_id": @"",
                @"w_ad_scene": @"default",
                @"w_error_code": @"3001",
                @"w_error_msg": @"AppLovin SDK not available",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_fill_fail"];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
        }
        
        [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] AppLovin SDK 不可用，无法加载激励视频广告"];
#endif
    });
}

- (void)closeRewardedVideo
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🚫 用户主动关闭激励视频广告"];
    self.isUserClosed = YES;
}

- (void)resumeRewardedVideo
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔄 恢复激励视频广告展示"];
    self.isUserClosed = NO;
    [self loadRewardedVideo];
}

- (void)checkPendingRewardedVideoDisplay
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔍 检查待展示的激励视频广告"];
    if (self.hasShowAd && self.isLoadRewardedVideo && !self.isUserClosed) {
        [self showRewardedVideo];
        self.hasShowAd = NO;
    }
}

#pragma mark - 场景化激励视频接口

- (void)showRewardedVideoForScene:(NSString *)scene
{
    if (self.isUserClosed) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ 用户已主动关闭广告，拒绝展示 (场景: %@)", scene];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ========== 开始展示场景化激励视频广告 =========="];
    [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 场景标识: %@", scene ?: @"未指定场景"];
    
    // 保存当前场景标识
    self.currentScene = scene;
    
    [[NSUserDefaults standardUserDefaults] setObject:@"2" forKey:@"WDOrientation"];
    
    // 每次展示前重置奖励状态
    self.receiveRewardForPlacement = NO;
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 重置奖励状态: receiveRewardForPlacement = NO"];
    
    // 埋点：SDK_ad_show_request 广告展示请求事件打点
    @try {
        NSDictionary *showRequestParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": @"",
            @"w_ad_scene": scene ?: @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
#if APPLOVIN_SDK_AVAILABLE
        if (self.rewardedAd && self.rewardedAd.adUnitIdentifier) {
            showRequestParams = @{
                @"w_ad_type": @"rewarded_video",
                @"w_ad_unit_id": self.rewardedAd.adUnitIdentifier,
                @"w_ad_scene": scene ?: @"default",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
        }
#endif
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_request" properties:showRequestParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_request (场景: %@)", scene];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
#if APPLOVIN_SDK_AVAILABLE
    MARewardedAd *adToShow = nil;
    NSString *selectedAdUnitId = self.currentAdUnitId;
    
    if (self.isDualAdEnabled) {
        // 双广告位模式 - 应用FB策略控制
        DMCommercialManager *commercialSDK = [DMCommercialManager sharedInstance];
        
        // 动态检查当前广告位是否应该展示
        BOOL isCurrentSecondary = [selectedAdUnitId isEqualToString:self.secondaryAdUnitId];
        BOOL shouldShow = [commercialSDK shouldShowAd:selectedAdUnitId adType:@"rewarded_video" isSecondaryAdUnit:isCurrentSecondary];
        
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🎯 FB策略检查：当前广告位 %@ (%@)", selectedAdUnitId, isCurrentSecondary ? @"备用" : @"主"];
        
        if (!shouldShow) {
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ⚠️ FB策略控制：当前%@广告位不应展示，尝试切换到另一个广告位", isCurrentSecondary ? @"备用" : @"主"];
            
            // 动态切换到另一个广告位
            NSString *alternativeAdUnitId;
            if ([selectedAdUnitId isEqualToString:self.primaryAdUnitId]) {
                alternativeAdUnitId = self.secondaryAdUnitId;
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔄 从主广告位切换到备用广告位: %@", alternativeAdUnitId];
            } else {
                alternativeAdUnitId = self.primaryAdUnitId;
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔄 从备用广告位切换到主广告位: %@", alternativeAdUnitId];
            }
            
            // 检查切换后的广告位是否可以展示
            BOOL isAlternativeSecondary = [alternativeAdUnitId isEqualToString:self.secondaryAdUnitId];
            BOOL alternativeShouldShow = [commercialSDK shouldShowAd:alternativeAdUnitId adType:@"rewarded_video" isSecondaryAdUnit:isAlternativeSecondary];
            
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🎯 FB策略检查：切换后广告位 %@ (%@)", alternativeAdUnitId, isAlternativeSecondary ? @"备用" : @"主"];
            
            if (alternativeShouldShow) {
                selectedAdUnitId = alternativeAdUnitId;
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ✅ 切换成功：使用%@广告位进行展示", isAlternativeSecondary ? @"备用" : @"主"];
            } else {
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ FB策略控制：所有广告位都不应展示，释放当前广告对象并重新加载"];
                @try {
                    NSDictionary *showFailParams = @{
                        @"w_ad_type": @"rewarded_video",
                        @"w_ad_unit_id": self.rewardedAd ? (self.rewardedAd.adUnitIdentifier ?: @"") : @"",
                        @"w_ad_scene": scene ?: @"default",
                        @"w_error_code": @"10002",
                        @"w_error_msg": @"FB policy blocked all ad units",
                        @"w_platform": @"MAX",
                        @"w_network": @"AppLovin"
                    };
                    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
                    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_fail"];
                } @catch (NSException *exception) {
                    [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
                }
                
                // 释放当前广告对象并重新加载
                self.primaryRewardedAd = nil;
                self.secondaryRewardedAd = nil;
                self.rewardedAd = nil;
                [self loadRewardedVideo];
                return;
            }
        } else {
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ✅ FB策略检查通过：当前%@广告位可以展示", isCurrentSecondary ? @"备用" : @"主"];
        }
        
        // 根据选择的广告位ID获取对应的广告实例
        if ([selectedAdUnitId isEqualToString:self.primaryAdUnitId] && self.primaryRewardedAd && [self.primaryRewardedAd isReady]) {
            adToShow = self.primaryRewardedAd;
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择主广告位进行展示: %@", selectedAdUnitId];
        } else if ([selectedAdUnitId isEqualToString:self.secondaryAdUnitId] && self.secondaryRewardedAd && [self.secondaryRewardedAd isReady]) {
            adToShow = self.secondaryRewardedAd;
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择备用广告位进行展示: %@", selectedAdUnitId];
        }
        self.currentAdUnitId = selectedAdUnitId;
    } else {
        // 单广告位模式，使用最优广告位选择逻辑
        selectedAdUnitId = [self selectOptimalAdUnitId];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 选择的最优广告位: %@", selectedAdUnitId];
        
        // 应用FB策略控制
        DMCommercialManager *commercialSDK = [DMCommercialManager sharedInstance];
        BOOL shouldShow = [commercialSDK shouldShowAd:selectedAdUnitId adType:@"rewarded_video" isSecondaryAdUnit:NO];
        
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🎯 FB策略检查：当前广告位 %@ (主)", selectedAdUnitId];
        
        if (!shouldShow) {
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ FB策略控制：主广告位不应展示，释放当前广告对象并重新加载"];
            @try {
                NSDictionary *showFailParams = @{
                    @"w_ad_type": @"rewarded_video",
                    @"w_ad_unit_id": self.rewardedAd ? (self.rewardedAd.adUnitIdentifier ?: @"") : @"",
                    @"w_ad_scene": scene ?: @"default",
                    @"w_error_code": @"10002",
                    @"w_error_msg": @"FB policy blocked",
                    @"w_platform": @"MAX",
                    @"w_network": @"AppLovin"
                };
                [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
                [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_fail"];
            } @catch (NSException *exception) {
                [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
            }
            
            // 释放当前广告对象并重新加载
            self.rewardedAd = nil;
            [self loadRewardedVideo];
            return;
        }
        
        adToShow = self.rewardedAd;
    }
    
    if (adToShow && [adToShow isReady])
    {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ✅ 场景化激励视频广告准备就绪，开始展示"];
        [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 广告实例: %@", adToShow];
        
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 获取根控制器: %@", rootViewController];
        
        [adToShow showAd];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 调用 showAd 完成 (场景: %@)", scene];
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ 场景化激励视频广告未准备就绪 (场景: %@)", scene];
        [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 广告实例存在: %@", adToShow ? @"YES" : @"NO"];
        [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 广告是否就绪: %@", (adToShow && [adToShow isReady]) ? @"YES" : @"NO"];
        
        // 埋点：SDK_ad_show_fail 广告展示失败事件打点
        @try {
            NSDictionary *showFailParams = @{
                @"w_ad_type": @"rewarded_video",
                @"w_ad_unit_id": adToShow ? (adToShow.adUnitIdentifier ?: @"") : @"",
                @"w_ad_scene": scene ?: @"default",
                @"w_error_code": @"4001",
                @"w_error_msg": @"Rewarded video ad not ready or not loaded",
                @"w_platform": @"MAX",
                @"w_network": @"AppLovin"
            };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_fail (场景: %@)", scene];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
        }
        
        self.hasShowAd = YES;
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 设置 hasShowAd = YES，将在广告加载完成后自动展示 (场景: %@)", scene];
        [self loadRewardedVideo];
    }
#else
    // 埋点：SDK_ad_show_fail 广告展示失败事件打点
    @try {
        NSDictionary *showFailParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": @"",
            @"w_ad_scene": scene ?: @"default",
            @"w_error_code": @"3001",
            @"w_error_msg": @"AppLovin SDK not available",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_fail (场景: %@)", scene];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
    [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ AppLovin SDK 不可用，无法显示场景化激励视频广告 (场景: %@)", scene];
#endif
}

- (BOOL)isRewardedVideoReadyForScene:(NSString *)scene
{
#if APPLOVIN_SDK_AVAILABLE
    BOOL isReady = (self.rewardedAd && [self.rewardedAd isReady]);
    [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] 检查场景化激励视频广告状态 (场景: %@): %@", scene ?: @"未指定场景", isReady ? @"就绪" : @"未就绪"];
    return isReady;
#else
    [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] AppLovin SDK 不可用，场景化激励视频广告不可用 (场景: %@)", scene ?: @"未指定场景"];
    return NO;
#endif
}

#pragma mark - MARewardedAdDelegate

#if APPLOVIN_SDK_AVAILABLE
- (void)didLoadAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] ✅ 激励视频广告加载成功"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 广告信息: %@", ad];
    
    self.isLoadRewardedVideo = YES;
    
    // 双广告位模式下更新对应广告位状态
    if (self.isDualAdEnabled) {
        if ([ad.adUnitIdentifier isEqualToString:self.currentPrimaryAdUnitId]) {
            self.isPrimaryAdLoaded = YES;
            self.primaryAdLoadTime = [[NSDate date] timeIntervalSince1970];
            if (ad.revenue) {
                self.primaryAdECPM = ad.revenue;
            }
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 主广告位加载成功: %@, ECPM: %.4f", ad.adUnitIdentifier, self.primaryAdECPM];
        } else if ([ad.adUnitIdentifier isEqualToString:self.currentSecondaryAdUnitId]) {
            self.isSecondaryAdLoaded = YES;
            self.secondaryAdLoadTime = [[NSDate date] timeIntervalSince1970];
            if (ad.revenue) {
                self.secondaryAdECPM = ad.revenue;
            }
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 备用广告位加载成功: %@, ECPM: %.4f", ad.adUnitIdentifier, self.secondaryAdECPM];
        }
    }
    
    // 重置重试状态
    [self resetRetryState];
    
    // 埋点：SDK_ad_fill_success 广告填充成功事件打点
    @try {
        NSMutableDictionary *fillSuccessParams = [@{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
            @"w_ad_scene": self.currentScene ?: @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        } mutableCopy];
        
        // 添加收益信息
        if (ad.revenue) {
            fillSuccessParams[@"w_ad_revenue"] = @(ad.revenue);
        }
        
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_success" properties:fillSuccessParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_fill_success"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
    // 双广告位模式下预加载另一个广告位
    [self loadDualAdsIfNeeded];
    
    // 通知统一代理
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didLoadAd:adType:)]) {
        [self.delegate dmAdManager:(id)self didLoadAd:ad.adUnitIdentifier adType:@"rewarded_video"];
    }
    
    // 如果有待展示的广告请求，立即展示
    if (self.hasShowAd && !self.isUserClosed) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🎯 检测到待展示请求，立即展示广告"];
        self.hasShowAd = NO;
        [self showRewardedVideo];
    }
}

- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error
{
    [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ 激励视频广告加载失败"];
    [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 错误信息: %@", error.message];
    [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 错误代码: %ld", (long)error.code];
    
    self.isLoadRewardedVideo = NO;
    
    // 双广告位模式下更新对应广告位状态
    if (self.isDualAdEnabled) {
        if ([adUnitIdentifier isEqualToString:self.currentPrimaryAdUnitId]) {
            self.isPrimaryAdLoaded = NO;
            [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 主广告位加载失败: %@", adUnitIdentifier];
            // 尝试切换到备用广告位
            [self switchToSecondaryAdIfNeeded];
        } else if ([adUnitIdentifier isEqualToString:self.currentSecondaryAdUnitId]) {
            self.isSecondaryAdLoaded = NO;
            [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 备用广告位加载失败: %@", adUnitIdentifier];
        }
    }
    
    // 更新失败统计
    [self updateFailureStatistics];
    
    // 埋点：SDK_ad_fill_fail 广告填充失败事件打点
    @try {
        NSDictionary *fillFailParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": adUnitIdentifier ?: @"",
            @"w_ad_scene": self.currentScene ?: @"default",
            @"w_error_code": @(error.code),
            @"w_error_msg": error.message ?: @"Unknown error",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_fill_fail"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
    // 通知统一代理
    NSError *sdkError = [NSError errorWithDomain:@"DualMediationSDK" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message ?: @"Rewarded video load failed"}];
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToLoadAd:adType:error:)]) {
        [self.delegate dmAdManager:(id)self didFailToLoadAd:adUnitIdentifier adType:@"rewarded_video" error:sdkError];
    }
    
    // 使用重试机制替代固定延迟重新加载
    if ([self shouldRetry]) {
        NSTimeInterval retryDelay = [self calculateRetryDelay];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔄 将在 %.1f 秒后重试 (第 %ld 次重试)", retryDelay, (long)(self.retryCount + 1)];
        [self scheduleRetryWithDelay:retryDelay];
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] ⚠️ 已达到最大重试次数或重试被暂停，停止重试"];
    }
}

- (void)didDisplayAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 👁️ 激励视频广告开始展示"];
    [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] AdInfo详情:"];
    [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded]   - AdNetwork: %@", ad.networkName ?: @"N/A"];
    [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded]   - AdUnitId: %@", ad.adUnitIdentifier ?: @"N/A"];
    
    // 埋点：SDK_ad_show_success 广告展示成功事件打点
    @try {
        NSDictionary *showSuccessParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
            @"w_ad_scene": self.currentScene ?: @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_success" properties:showSuccessParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_success"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }

    // 新增：AD_RV_show（场景+收入，收入单位mUSD）
    @try {
        NSString *scene = self.currentScene ?: @"default";
        double ecpm = ad.revenue * 1000.0;
        NSDictionary *rvShowParams = @{ @"w_scene": scene, @"w_revenue": @(ecpm),@"w_auctionId":[DMConfigReader auctionId] };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"AD_RV_show" jsonStr:rvShowParams];
        
        ADJAdRevenue *adjustAdRevenue = [[ADJAdRevenue alloc] initWithSource:@"applovin_max_sdk"];
        [adjustAdRevenue setRevenue:ad.revenue currency:@"USD"];
        [adjustAdRevenue setAdRevenueNetwork:ad.networkName];
        [adjustAdRevenue setAdRevenueUnit:ad.adUnitIdentifier];
        [adjustAdRevenue setAdRevenuePlacement:ad.placement];
        [adjustAdRevenue addPartnerParameter:@"ad_format" value:ad.format.label];
        [adjustAdRevenue addPartnerParameter:@"ad_unit_id" value:ad.adUnitIdentifier];
        [Adjust trackAdRevenue:adjustAdRevenue];
        
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件上报: AD_RV_show, w_scene=%@, w_revenue: %.2f", scene, ecpm];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件上报异常: %@", exception.reason];
    }
    
    // 场景化回调转发
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowRewardedVideoForScene:adId:)]) {
        [self.delegate dmAdManager:nil didShowRewardedVideoForScene:self.currentScene adId:ad.adUnitIdentifier ?: @"unknown"];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 场景化回调转发: didShowRewardedVideoForScene (场景: %@)", self.currentScene];
    }
}

- (void)didClickAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 👆 激励视频广告被点击"];
    [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] AdInfo详情:"];
    [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded]   - AdNetwork: %@", ad.networkName ?: @"N/A"];
    [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded]   - AdUnitId: %@", ad.adUnitIdentifier ?: @"N/A"];
    
    // 埋点：SDK_ad_show_click 广告点击事件打点
    @try {
        NSDictionary *clickParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
            @"w_ad_scene": self.currentScene ?: @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_click" properties:clickParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_click"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
    // 通知统一代理
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didClickAd:adType:)]) {
        [self.delegate dmAdManager:(id)self didClickAd:ad.adUnitIdentifier adType:@"rewarded_video"];
    }
}

- (void)didRewardUserForAd:(MAAd *)ad withReward:(MAReward *)reward
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🎉 用户获得奖励！"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 奖励类型: %@", reward.label];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 奖励数量: %ld", (long)reward.amount];
    
    self.receiveRewardForPlacement = YES;
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 设置奖励状态: receiveRewardForPlacement = YES"];
    
    // 埋点：SDK_ad_show_completed 广告播放完成事件打点
    @try {
        NSDictionary *completedParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
            @"w_ad_scene": self.currentScene ?: @"default",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_completed" properties:completedParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_completed"];
        
        // 新增：AD_RV_Completed（场景+收入，收入单位mUSD）
        @try {
            NSString *scene = self.currentScene ?: @"default";
            double ecpm = ad.revenue * 1000.0;
            NSDictionary *rvCompletedParams = @{ @"w_scene": scene, @"w_revenue": @(ecpm) };
            [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"AD_RV_Completed" jsonStr:rvCompletedParams];
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件上报: AD_RV_Completed, w_scene=%@, w_revenue: %.2f", scene, ecpm];
        } @catch (NSException *exception) {
            [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件上报异常: %@", exception.reason];
        }
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
    // 通知统一代理
    NSDictionary *rewardInfo = @{
        @"type": reward.label ?: @"",
        @"amount": @(reward.amount)
    };
    
    // TODO: 需要根据项目配置发送 Adjust 事件
    // 等待项目中的 Adjust token 配置
    [IMLogUtils debug:IMLogTagAd format:@"🎬 [MAX Rewarded] Adjust 奖励事件待配置"];
}

- (void)didHideAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 👻 激励视频广告关闭"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 最终奖励状态: %@", self.receiveRewardForPlacement ? @"已获得奖励" : @"未获得奖励"];
    
    // 通知统一代理
    // 场景化关闭回调转发
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didCloseRewardedVideoForScene:adId:isUserRewarded:)]) {
        [self.delegate dmAdManager:nil didCloseRewardedVideoForScene:self.currentScene adId:ad.adUnitIdentifier ?: @"unknown" isUserRewarded:self.receiveRewardForPlacement];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 场景化回调转发: didCloseRewardedVideoForScene (场景: %@, 奖励: %@)", self.currentScene, self.receiveRewardForPlacement ? @"是" : @"否"];
    }
    // 重置场景标识
    self.currentScene = nil;
    
    // 广告关闭后预加载下一个
    self.isLoadRewardedVideo = NO;
    if (!self.isUserClosed) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔄 广告关闭，开始预加载下一个激励视频广告"];
        [self loadRewardedVideo];
    }
}

- (void)didFailToDisplayAd:(nonnull MAAd *)ad withError:(nonnull MAError *)error { 
    [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ 激励视频广告展示失败"];
    [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 错误信息: %@", error.message];
    [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 错误代码: %ld", (long)error.code];
    
    // 更新失败统计
    [self updateFailureStatistics];
    
    // 埋点：SDK_ad_show_fail 广告展示失败事件打点
    @try {
        NSDictionary *showFailParams = @{
            @"w_ad_type": @"rewarded_video",
            @"w_ad_unit_id": ad.adUnitIdentifier ?: @"",
            @"w_ad_scene": self.currentScene ?: @"default",
            @"w_error_code": @(error.code),
            @"w_error_msg": error.message ?: @"Unknown error",
            @"w_platform": @"MAX",
            @"w_network": @"AppLovin"
        };
        [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点: SDK_ad_show_fail"];
    } @catch (NSException *exception) {
        [IMLogUtils error:IMLogTagAd format:@"🎬 [MAX Rewarded] 事件打点异常: %@", exception.reason];
    }
    
    // 通知统一代理
    NSError *sdkError = [NSError errorWithDomain:@"DualMediationSDK" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message ?: @"Rewarded video display failed"}];
    
    // 场景化失败回调转发
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowRewardedVideoForScene:error:)]) {
        NSError *nsError = [NSError errorWithDomain:@"DualMediationMAXRewarded" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message ?: @"展示失败"}];
        [self.delegate dmAdManager:nil didFailToShowRewardedVideoForScene:self.currentScene error:nsError];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 场景化回调转发: didFailToShowRewardedVideoForScene (场景: %@)", self.currentScene];
    }
    // 重置场景标识
    self.currentScene = nil;
    
    // 使用重试机制重新加载广告
    if ([self shouldRetry]) {
        NSTimeInterval retryDelay = [self calculateRetryDelay];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔄 展示失败，将在 %.1f 秒后重试加载 (第 %ld 次重试)", retryDelay, (long)(self.retryCount + 1)];
        [self scheduleRetryWithDelay:retryDelay];
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] ⚠️ 展示失败，已达到最大重试次数或重试被暂停，停止重试"];
        // 直接重新加载一次
        [self loadRewardedVideo];
    }
}

#pragma mark - MAAdRevenueDelegate
- (void)didPayRevenueForAd:(MAAd *)ad
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 💸 ========== 收到 Revenue Data ==========="];
    
    if (!ad || ad.revenue <= 0) {
        [IMLogUtils warning:IMLogTagAd format:@"🎬 [MAX Rewarded] ❌ Revenue data 无效或收入为空"];
        return;
    }

    double revenueUSD = ad.revenue;
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 💰 Revenue 收入详情:"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded]   - AdUnitId: %@", ad.adUnitIdentifier ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded]   - AdNetwork: %@", ad.networkName ?: @"N/A"];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded]   - Revenue: $%.6f", revenueUSD];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded]   - CreativeId: %@", ad.creativeIdentifier ?: @"N/A"];
    
    NSString *AdUnitId = ad.adUnitIdentifier;
    NSString *ad_format = @"rewarded_video";
    NSString *adSource = @"unknown"; // 主广告位还是备用广告位
    
    // 判断广告源（主/备用广告位）- 仅针对激励视频
    if ([AdUnitId isEqualToString:[DMConfigReader primaryRewardAdUnitIdForMAX]]) {
        adSource = @"primary";
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"RV_RevenueUSD"];
    } else if ([AdUnitId isEqualToString:[DMConfigReader secondaryRewardAdUnitIdForMAX]]) {
        adSource = @"secondary";
        [[NSUserDefaults standardUserDefaults] setDouble:revenueUSD forKey:@"RV_RevenueUSD"];
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded]   - ad_format: %@", ad_format];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded]   - ad_source: %@", adSource];
    
    // ========== DMCommercialManager 策略集成（仅限激励视频）==========
    DMCommercialManager *commercialSDK = [DMCommercialManager sharedInstance];
    
    // 1. 记录广告位性能数据
    [commercialSDK recordAdUnitPerformance:AdUnitId
                                      ecpm:revenueUSD
                                 fillRate:1.0
                                 clickRate:0.0
                                 isSuccess:YES];
    
    // 2. 应用FB策略控制（激励视频）
    BOOL shouldSwitchAd = [commercialSDK shouldSwitchAdForType:@"rewarded_video"
                                                    adUnitId:AdUnitId];
    if (shouldSwitchAd) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🔄 FB策略触发：建议切换广告位"];
        // 通知切换广告位
        [self switchToSecondaryAdIfNeeded];
    }
    
    // 3. ECPM比较和广告位优化（仅限激励视频的主备广告位）
    if ([adSource isEqualToString:@"primary"] || [adSource isEqualToString:@"secondary"]) {
        NSString *primaryAdUnitId = [DMConfigReader primaryRewardAdUnitIdForMAX];
        NSString *secondaryAdUnitId = [DMConfigReader secondaryRewardAdUnitIdForMAX];
        
        if (primaryAdUnitId && secondaryAdUnitId) {
            NSString *optimalAdUnitId = [commercialSDK compareAdUnitsAndSelectOptimal:primaryAdUnitId
                                                                      secondaryAdUnitId:secondaryAdUnitId];
            [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 🎯 ECPM比较结果：最优广告位 = %@", optimalAdUnitId];
        }
    }
    
    // ========== 原有上报逻辑保持不变 ==========
    // 1. 上报 Taichi
    NSNumber *revenueMicros = @(revenueUSD * 1000);
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] Taichi 上报完成: %@ micros", revenueMicros];

#if FIREBASE_AVAILABLE
    // 2. Firebase 埋点
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"ad_platform"] = @"MAX";
    params[@"ad_unit"] = ad.adUnitIdentifier ?: @"";
    params[@"ad_format"] = ad_format;
    params[@"ad_source"] = ad.networkName ?: @"";
    params[@"ad_unit_name"] = ad.adUnitIdentifier ?: @"";
    params[@"ad_unit_source"] = adSource; // 新增：标识主/备用广告位
    params[@"value"] = @(revenueUSD);
    params[@"currency"] = @"USD";
    [FIRAnalytics logEventWithName:@"ad_impression" parameters:params];
    [FIRAnalytics logEventWithName:@"Ad_Impression_Revenue" parameters:params];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] Firebase 埋点完成"];
    
    // 3. Facebook 事件上报
    NSMutableDictionary *fbParams = [NSMutableDictionary dictionary];
    fbParams[@"ad_platform"] = @"MAX";
    fbParams[@"ad_unit"] = ad.adUnitIdentifier ?: @"";
    fbParams[@"ad_format"] = ad_format;
    fbParams[@"ad_source"] = ad.networkName ?: @"";
    fbParams[@"ad_unit_name"] = ad.adUnitIdentifier ?: @"";
    fbParams[@"ad_unit_source"] = adSource;
    fbParams[@"value"] = @(revenueUSD);
    fbParams[@"currency"] = @"USD";
    
    [FBSDKAppEvents.shared logEvent:@"ad_impression" parameters:fbParams];
    [FBSDKAppEvents.shared logEvent:@"Ad_Impression_Revenue" parameters:fbParams];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] Facebook 事件上报完成"];
#endif

    // 4. 10个等级的太极打点机制
    [self reportMultiLevelTaichiRevenue:revenueUSD adFormat:ad_format adSource:adSource];

    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 💸 Revenue Data 处理完成"];
}

#endif

#pragma mark - 10个等级的太极打点机制

// =============== 配置：10 档（0.01 ~ 0.10，每档 +0.01） ===============
static inline NSArray<NSNumber *> *WDRevenueTiersUSD(void) {
    return @[@0.01, @0.02, @0.03, @0.04, @0.05, @0.06, @0.07, @0.08, @0.09, @0.10];
}

// 事件名与阈值一一对应，001~010 分别对应 0.01~0.10
static inline NSArray<NSString *> *WDRevenueEventNames(void) {
    return @[
        @"Total_Ads_Revenue_001", // 0.01
        @"Total_Ads_Revenue_002", // 0.02
        @"Total_Ads_Revenue_003", // 0.03
        @"Total_Ads_Revenue_004", // 0.04
        @"Total_Ads_Revenue_005", // 0.05
        @"Total_Ads_Revenue_006", // 0.06
        @"Total_Ads_Revenue_007", // 0.07
        @"Total_Ads_Revenue_008", // 0.08
        @"Total_Ads_Revenue_009", // 0.09
        @"Total_Ads_Revenue_010"  // 0.10
    ];
}

// =============== 本地持久化 Key ===============
static NSString * const kWDTotalUSDKey = @"TaichiTroasTotalUSD"; // 累计总额(USD)
static NSString * const kWDLastTierKey = @"TaichiTroasLastTier"; // 已触发最高档位 index（-1 表示未触发）

// =============== 串行队列（防并发竞态） ===============
static dispatch_queue_t WDRevenueQueue(void) {
    static dispatch_queue_t q;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        q = dispatch_queue_create("com.wd.revenue.milestones", DISPATCH_QUEUE_SERIAL);
    });
    return q;
}

#pragma mark - 10 档里程碑上报（累计总额 + 已触发最高档位）

/**
 里程碑模型：
 - 仅维护 累计总额(totalUSD) 与 已触发最高档位(lastTier)
 - 每次新增 delta 后，计算最高可达档位 currentTier
 - 若 currentTier > lastTier：从 lastTier+1 ~ currentTier 依次上报（可能补齐多个档）
 - 避免"每档独立缓存"的重复/漏报/余量丢失问题
*/
- (void)reportMultiLevelTaichiRevenue:(double)revenueUSD
                             adFormat:(NSString *)adFormat
                             adSource:(NSString *)adSource
{
    if (revenueUSD <= 0) {
        [IMLogUtils warning:IMLogTagAd format:@"⚠️ [RevTier] delta<=0，忽略"];
        return;
    }

    dispatch_async(WDRevenueQueue(), ^{
        NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;

        // 1) 更新累计
        double total = [ud doubleForKey:kWDTotalUSDKey];
        double newTotal = total + revenueUSD;
        [ud setDouble:newTotal forKey:kWDTotalUSDKey];

        [IMLogUtils info:IMLogTagAd format:@"🧮 [RevTier] 累计更新: old=%.6f → new=%.6f (+%.6f)", total, newTotal, revenueUSD];

        // 2) 计算当前最高可达档位
        NSArray<NSNumber *> *tiers = WDRevenueTiersUSD();
        NSInteger currentTier = -1;
        for (NSInteger i = tiers.count - 1; i >= 0; i--) {
            if (newTotal >= tiers[i].doubleValue) {
                currentTier = i; break;
            }
        }

        NSInteger lastTier = -1;
        if ([ud objectForKey:kWDLastTierKey] != nil) {
            lastTier = (NSInteger)[ud integerForKey:kWDLastTierKey];
        }

        [IMLogUtils info:IMLogTagAd format:@"📐 [RevTier] lastTier=%ld | currentTier=%ld", (long)lastTier, (long)currentTier];

        // 3) 补齐新跨越的档位
        if (currentTier > lastTier) {
            NSArray<NSString *> *events = WDRevenueEventNames();
            for (NSInteger i = lastTier + 1; i <= currentTier; i++) {
                NSString *eventName = events[i];
                NSNumber *threshold = tiers[i];

#if FIREBASE_AVAILABLE
                // Firebase：事件名与门槛一一对应
                NSDictionary *fa = @{
                    kFIRParameterValue: @(newTotal),         // 传累计总额（便于分析）
                    kFIRParameterCurrency: @"USD",
                    @"ad_format": adFormat ?: @"",
                    @"ad_source": adSource ?: @"",
                    @"tier_index": @(i),
                    @"tier_threshold": threshold
                };
                [FIRAnalytics logEventWithName:eventName parameters:fa];

                // Facebook：同样触发 FB_ 前缀的事件
                NSDictionary *fb = @{
                    FBSDKAppEventParameterNameCurrency: @"USD",
                    @"ad_format": adFormat ?: @"",
                    @"ad_source": adSource ?: @"",
                    @"tier_index": @(i),
                    @"tier_threshold": threshold
                };
                [[FBSDKAppEvents shared]logEvent:[@"FB_" stringByAppendingString:eventName] valueToSum:newTotal parameters:fb];
#endif
                
                [IMLogUtils info:IMLogTagAd format:@"🚩 [RevTier] 触发档位=%ld | event=%@ | threshold=%.2f | total=%.6f",
                      (long)i, eventName, threshold.doubleValue, newTotal];
            }

            [ud setInteger:currentTier forKey:kWDLastTierKey];
            [IMLogUtils info:IMLogTagAd format:@"📝 [RevTier] 更新 lastTier=%ld", (long)currentTier];
        } else {
            [IMLogUtils info:IMLogTagAd format:@"⏭️ [RevTier] 未跨越新档位，不触发事件"];
        }

        // 不需要 synchronize；系统会自行刷盘
    });
}

#pragma mark - 调试/维护辅助（可选）

- (void)wd_resetRevenueMilestonesForDebug {
    NSUserDefaults *ud = NSUserDefaults.standardUserDefaults;
    [ud removeObjectForKey:kWDTotalUSDKey];
    [ud removeObjectForKey:kWDLastTierKey];
    [IMLogUtils info:IMLogTagAd format:@"🧹 [RevTier] 已清除累计&档位状态（仅调试）"];
}

#pragma mark - 重试机制相关方法

- (void)initializeRetrySettings
{
    [IMLogUtils info:IMLogTagSDKInit format:@"🎬 [MAX Rewarded] 初始化重试设置"];
    
    // 设置重试参数
    self.maxRetryCount = 3;           // 最大重试次数
    self.baseRetryInterval = 2.0;     // 基础重试间隔（秒）
    
    // 重置重试状态
    [self resetRetryState];
    
    [IMLogUtils info:IMLogTagSDKInit format:@"🎬 [MAX Rewarded] 重试设置完成 - 最大重试次数: %ld, 基础间隔: %.1f秒", (long)self.maxRetryCount, self.baseRetryInterval];
}

- (void)resetRetryState
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 重置重试状态"];
    
    self.retryCount = 0;
    self.totalFailureCount = 0;
    self.totalLoadAttempts = 0;
    self.lastRetryTime = 0;
    self.isRetryPaused = NO;
    
    // 取消现有的重试定时器
    [self cancelRetryTimer];
}

- (void)scheduleRetryWithDelay:(NSTimeInterval)delay
{
    if (self.isRetryPaused) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 重试已暂停，跳过调度"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 安排 %.1f 秒后重试", delay];
    
    // 取消现有的重试定时器
    [self cancelRetryTimer];
    
    // 创建新的重试定时器
    dispatch_async(dispatch_get_main_queue(), ^{
        self.retryTimer = [NSTimer scheduledTimerWithTimeInterval:delay
                                                           target:self
                                                         selector:@selector(performRetry)
                                                         userInfo:nil
                                                          repeats:NO];
    });
    
    self.lastRetryTime = [[NSDate date] timeIntervalSince1970];
}

- (void)cancelRetryTimer
{
    if (self.retryTimer && [self.retryTimer isValid]) {
        [self.retryTimer invalidate];
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 取消重试定时器"];
    }
    self.retryTimer = nil;
}

- (BOOL)shouldRetry
{
    // 检查是否超过最大重试次数
    if (self.retryCount >= self.maxRetryCount) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 已达到最大重试次数 (%ld)，停止重试", (long)self.maxRetryCount];
        return NO;
    }
    
    // 检查是否暂停重试
    if (self.isRetryPaused) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 重试已暂停"];
        return NO;
    }
    
    // 检查失败率是否过高
    double failureRate = [self calculateFailureRate];
    if (failureRate > 0.8 && self.totalLoadAttempts > 5) {
        [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 失败率过高 (%.2f%%)，暂停重试", failureRate * 100];
        self.isRetryPaused = YES;
        return NO;
    }
    
    return YES;
}

- (NSTimeInterval)calculateRetryDelay
{
    // 指数退避算法：baseRetryInterval * (2^retryCount)
    NSTimeInterval delay = self.baseRetryInterval * pow(2, self.retryCount);
    
    // 限制最大延迟时间为60秒
    delay = MIN(delay, 60.0);
    
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 计算重试延迟: %.1f秒 (第%ld次重试)", delay, (long)self.retryCount + 1];
    
    return delay;
}

- (void)updateFailureStatistics
{
    self.totalFailureCount++;
    self.totalLoadAttempts++;
    
    double failureRate = [self calculateFailureRate];
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 更新失败统计 - 总失败: %ld, 总尝试: %ld, 失败率: %.2f%%", 
     (long)self.totalFailureCount, (long)self.totalLoadAttempts, failureRate * 100];
}

- (double)calculateFailureRate
{
    if (self.totalLoadAttempts == 0) {
        return 0.0;
    }
    
    return (double)self.totalFailureCount / (double)self.totalLoadAttempts;
}

- (void)performRetry
{
    [IMLogUtils info:IMLogTagAd format:@"🎬 [MAX Rewarded] 执行重试 (第%ld次)", (long)self.retryCount + 1];
    
    self.retryCount++;
    
    // 根据是否启用双广告位模式选择加载方式
    if (self.isDualAdEnabled) {
        [self loadDualRewardedAds];
    } else {
        [self loadRewardedVideo];
    }
}

@end
